package com.eeepay.eeepay_v2.activity;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.util.BtnStyleUtil;
import com.eeepay.eeepay_v2.util.ConfigPorperties;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.GrpcUtils;
import com.eeepay.v2_library.ui.ABBaseActivity;
import com.eeepay.v2_library.util.ABRegUtil;

import java.util.concurrent.TimeUnit;

import cn.eeepay.api.grpc.nano.UpdatePwdApiServiceGrpc;
import cn.eeepay.api.grpc.nano.UpdatePwdProto;
import io.grpc.ManagedChannel;

/**
 * Created by zw on 2016/4/6 0006.
 * 找回密码发送验证码界面
 */
public class AuthCodeActivity extends ABBaseActivity implements View.OnClickListener {

    private static final int send_SMS = 0;//发送验证码
    private static final int auth_phone = 1;//验证手机号以及验证码

    private EditText et_phone, et_SMSCode;//短信验证码
    private TextView tv_sendSMS;//发送短信
    private Button btn_confirm;

    private boolean isMsg = false;
    private CountDownTimer mCountDownTimer;

    private String phone;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_auth_code;
    }

    @Override
    protected void initWidget() {
        et_phone = getViewById(R.id.et_phone);
        et_SMSCode = getViewById(R.id.et_SMS_code);
        tv_sendSMS = getViewById(R.id.tv_send_SMS);
        btn_confirm = getViewById(R.id.btn_confirm);
        BtnStyleUtil.inintBtnDefaultStyle(mContext,btn_confirm);
//        btn_confirm.setEnabled(false);
//        btn_confirm.setBackgroundResource(R.drawable.icon_no_next_step);
    }

    @Override
    protected void eventOnClick() {
        btn_confirm.setOnClickListener(this);
        tv_sendSMS.setOnClickListener(this);

        et_SMSCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s != null && s.length() == 6) {
                    isMsg = true;
                } else {
                    isMsg = false;
                }

                if (isMsg) {
                    BtnStyleUtil.settingBtnStyle(mContext,btn_confirm);
//                    btn_confirm.setEnabled(true);
//                    btn_confirm.setBackgroundResource(R.drawable.icon_next_step);
                } else {
                    BtnStyleUtil.inintBtnDefaultStyle(mContext,btn_confirm);
//                    btn_confirm.setEnabled(false);
//                    btn_confirm.setBackgroundResource(R.drawable.icon_no_next_step);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        mCountDownTimer = new CountDownTimer(60 * 1000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                tv_sendSMS.setText(String.format("%1$d s", millisUntilFinished / 1000));
            }

            @Override
            public void onFinish() {
                tv_sendSMS.setText("重新获取");
                tv_sendSMS.setEnabled(true);
            }
        };
    }

    @Override
    protected void sendHttpRequest(int taskId) {
        showProgressDialog();
        GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT
                , taskId, new GrpcUtils.AsyncTaskListener() {

            @Override
            public Object doInBack(ManagedChannel channel, int taskId) {

                switch (taskId) {
                    case send_SMS://发送验证码
                        UpdatePwdApiServiceGrpc.UpdatePwdApiServiceBlockingStub stub = UpdatePwdApiServiceGrpc
                                .newBlockingStub(channel)
                                .withDeadlineAfter(Constant.grpc_time_out, TimeUnit.SECONDS);
                        UpdatePwdProto.PhoneCodeRequest request = new UpdatePwdProto.PhoneCodeRequest();
                        request.phoneNo = et_phone.getText().toString().trim();
                        request.teamId = ConfigPorperties.getInstance().getTeamId();
                        UpdatePwdProto.UpdatePwdResponse response = stub.validCode(request);
                        return response;
                    case auth_phone:
                        return authPhone(channel);

                }
                return null;
            }

            @Override
            public void updateUI(Object result, int taskId) {
                dismissProgressDialog();
                if (result == null) {
                    showToast("操作失败");
                    return;
                }
                UpdatePwdProto.UpdatePwdResponse response = (UpdatePwdProto.UpdatePwdResponse) result;
                switch (taskId) {
                    case send_SMS://发送验证码
                        showToast(response.resMsg.msg);
                        break;
                    case auth_phone:
                        if (response.resMsg.status) {
                            Bundle bundle = new Bundle();
                            bundle.putString("phone", phone);
                            bundle.putString(Constant.INTENT_FLAG, Constant.FIND_PWD);
                            goActivity(PwdActivity.class, bundle);
                            finish();
                        } else {
                            showToast(response.resMsg.msg);
                        }
                        break;
                }
            }

        });

    }

    /**
     *  验证手机号以及验证码
     * @param channel
     * @return
     */
    private UpdatePwdProto.UpdatePwdResponse authPhone(ManagedChannel channel){
        UpdatePwdApiServiceGrpc.UpdatePwdApiServiceBlockingStub stub = UpdatePwdApiServiceGrpc
                .newBlockingStub(channel)
                .withDeadlineAfter(Constant.grpc_time_out, TimeUnit.SECONDS);
        UpdatePwdProto.PhoneCodeRequest request = new UpdatePwdProto.PhoneCodeRequest();
        UpdatePwdProto.UpdatePwdResponse response = null;
        try {
            request.phoneNo = phone;
            request.validCode = et_SMSCode.getText().toString().trim();
            request.teamId = ConfigPorperties.getInstance().getTeamId();
            response = stub.phoneValidCode(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_send_SMS:
                phone = et_phone.getText().toString().trim();
                if(ABRegUtil.isRegiest(phone, ABRegUtil.REG_PHONE_CHINA)){
                    mCountDownTimer.start();
                    tv_sendSMS.setEnabled(false);
                    sendHttpRequest(send_SMS);
                }else{
                    showToast("不是正确的手机号");
                }

                break;
            case R.id.btn_confirm:
                sendHttpRequest(auth_phone);
                break;
        }
    }

}
